//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "framework\fn_setMissionInstance.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;
private ["_InstanceList","_InstanceValues","_instance","_id","_index","_value","_NewInstanceValues"];
DEFAULT_PARAM(_id,0,TMF_SERVER_INSTANCE_ID);
DEFAULT_PARAM(_NewInstanceValues,1,(call FFUNC(hashEmpty)));

if (isnil QGVAR(STORING_MISSION_INSTANCE_BUSY)) then { GVAR(STORING_MISSION_INSTANCE_BUSY) = -1; };
waituntil {(GVAR(STORING_MISSION_INSTANCE_BUSY) < time)};
GVAR(STORING_MISSION_INSTANCE_BUSY) = time + 10;

if (typename _id == typename "") then {
	_InstanceList = JIPGETVAR(QGVAR(MISSION_INSTANCES),[]);
	_InstanceValues = JIPGETVAR(QGVAR(MISSION_INSTANCE_VALUES),[]);
	_index = _InstanceList find _id;
	if (_index < 0) then {
		_index = count _InstanceList;
		_InstanceList set [_index, _id];
		_instance = (call FFUNC(hashEmpty));
		_instance = [_instance, TMF_HK_INSTANCE_ID,_id] call FFUNC(HashSet);
		_InstanceValues set [_index, _instance];
		JIPSETVAR(QGVAR(MISSION_INSTANCES),_InstanceList);
		JIPSETVAR(QGVAR(MISSION_INSTANCE_VALUES),_InstanceValues);
		TRACE_1("Created new Instance",ARR_2(_index, _id));
	};
	If (_index >= count (_InstanceValues)) then {
		_instance = (call FFUNC(hashEmpty));
		_instance = [_instance, TMF_HK_INSTANCE_ID,_id] call FFUNC(HashSet);
		_InstanceValues set [_index, _instance];
		JIPSETVAR(QGVAR(MISSION_INSTANCE_VALUES),_InstanceValues);
		TRACE_1("Created new Instance Values",ARR_2(_index, _id));
	};
	_instance = _InstanceValues select _index;
	// Now we check if we got the values back of the right instance
	_value = [_instance, TMF_HK_INSTANCE_ID,"",THIS_FILE] call FFUNC(hashGet);
	if (_value == _id) then {
		_NewInstanceValues = [_NewInstanceValues, TMF_HK_INSTANCE_ID,_id] call FFUNC(HashSet);
		_InstanceValues set [_index, _NewInstanceValues];
		JIPSETVAR(QGVAR(MISSION_INSTANCE_VALUES),_InstanceValues);
	} else {
		ERROR_1("Found instance values do not match",ARR_3(_id,_index,_value));
	};
};

GVAR(STORING_MISSION_INSTANCE_BUSY) = -1;
TRACE("End");
TMFPROFILERSTOP;
